﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using RaisingForce.Raise.Language.Rules;
using RaisingForce.Raise.ObjectModel;

namespace RaisingForce.Raise.Language.Model.Rules
{
    sealed public class RuleSetCollection :
        NotNullKeyedCollection<string, RuleSet>
    {
        #region Constructors

        public RuleSetCollection()
            : base()
        { }

        #endregion

        #region Private Declarations

        private int nameIndex = 1;

        private void incrementNameIndex()
        {
            checked
            {
                this.nameIndex += 1;
            }
        }

        [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant(nameIndex > 0);
        }

        private const string nameTemplate = "RuleSet{0}";

        private static string getName(int nameIndex)
        {
            Contract.Requires(nameIndex > 0);
            Contract.Ensures(KnowledgeRules.NameIsValid(Contract.Result<string>()));
            string name = string.Format(nameTemplate, nameIndex);
            Contract.Assume(KnowledgeRules.NameIsValid(name));
            return name;
        }

        #endregion

        #region Public CreateRuleSet Methods

        public RuleSet CreateRuleSet()
        {
            Contract.Ensures(Contract.Result<RuleSet>() != null);
            Contract.Ensures(this.Contains(Contract.Result<RuleSet>()));
            return this.createRuleSet(
                name =>
                {
                    Contract.Assume(name != null);
                    return new RuleSet(name);
                });
        }

        public RuleSet CreateRuleSet(IList<Rule> rules)
        {
            Contract.Ensures(Contract.Result<RuleSet>() != null);
            Contract.Ensures(this.Contains(Contract.Result<RuleSet>()));
            return this.createRuleSet(
                name =>
                {
                    Contract.Assume(name != null);
                    return new RuleSet(name, rules);
                });
        }

        private RuleSet createRuleSet(Func<string, RuleSet> ruleSetFabric)
        {
            Contract.Requires(ruleSetFabric != null);
            Contract.Ensures(Contract.Result<RuleSet>() != null);
            Contract.Ensures(this.Contains(Contract.Result<RuleSet>()));
            string name = this.GetNextName();
            RuleSet ruleSet = ruleSetFabric(name);
            this.Add(ruleSet);
            return ruleSet;
        }

        #endregion

        #region Public Methods

        public string GetNextName()
        {
            Contract.Ensures(KnowledgeRules.NameIsValid(Contract.Result<string>()));
            while (true)
            {
                string name = RuleSetCollection.getName(this.nameIndex);
                if (!this.Contains(name))
                {   // correct name was found, break cycle
                    return name;
                }
                // incrementing after return, because we can ignore returning value
                this.incrementNameIndex();
            }
        }

        public RuleSetDataCollection GetData()
        {
            Contract.Ensures(Contract.Result<RuleSetDataCollection>() != null);
            RuleSetDataCollection ruleSets = new RuleSetDataCollection();
            IEnumerable<RuleSetData> ruleSetDataItems =
                this.Select(ruleSet => ruleSet.GetData());
            foreach (RuleSetData ruleSetData in ruleSetDataItems)
            {
                ruleSets.Add(ruleSetData);
            }
            return ruleSets;
        }

        #endregion

        #region Base Overrides

        protected override string GetKeyForItem(RuleSet item)
        {
            return item.Name;
        }

        #endregion

        #region Static Methods

        public static RuleSetCollection CreateFromData(
            RuleSetDataCollection ruleSetDataCollection,
            IWordFabric wordFabric)
        {
            if (ruleSetDataCollection == null)
            {
                throw new ArgumentNullException("ruleSetDataCollection");
            }
            if (wordFabric == null)
            {
                throw new ArgumentNullException("wordFabric");
            }
            Contract.Ensures(Contract.Result<RuleSetCollection>() != null);
            Contract.EndContractBlock();
            RuleSetCollection ruleSetCollection = new RuleSetCollection();
            IEnumerable<RuleSet> ruleSetItems = ruleSetDataCollection
                .Select(ruleSetData => RuleSet.CreateFromData(ruleSetData, wordFabric));
            foreach (RuleSet ruleSet in ruleSetItems)
            {
                ruleSetCollection.Add(ruleSet);
            }
            return ruleSetCollection;
        }

        #endregion
    }
}
